package com.mingle.iwalk;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class POIActivity extends Activity {

	private Spinner mTheme;
	private EditText mDescription;
	private ImageView mPhoto;
	
	private StatusButton mPhotoBtn;
	private StatusButton mLocationBtn;
	private StatusButton mVoiceBtn;
	private StatusButton mUploadBtn;
	
	private IndicateLayout mPicIndicator;
	private IndicateLayout mLocIndicator;
	private IndicateLayout mVoiceIndicator;
	private IndicateLayout mTrackIndicator;
	private IndicateLayout mUploadIndicator;
	
	private TravelerDB mDB;
	private POIInfo mInfo;
	private LocationManager mLocManager;
	private File mWorkFolder;

	
	private static final int REQUEST_CODE_CAMERA = 0;
	private static final int REQUEST_CODE_PICVIEW = 1;
	private static final int REQUEST_CODE_PICEDIT = 2;
	
	private final int HANDLER_MSG_UPDATE_LOC = 0;
	private final int HANDLER_MSG_UPLOAD_INFO_START = 1;
	private final int HANDLER_MSG_UPLOAD_INFO_END = 2;
	
	private final int LOCATE_STATE_NO_LOC = 0;
	private final int LOCATE_STATE_LOCATING = 1;
	private final int LOCATE_STATE_HAS_LOC = 2;
	
	private final int PIC_STATE_NO_PIC = 0;
	private final int PIC_STATE_HAS_PIC = 1;
	
	private final int VOICE_STATE_NO_VO = 0;
	private final int VOICE_STATE_RECORDING = 1;
	private final int VOICE_STATE_HAS_VO = 2;
	
	private final int UPLOAD_STATE_NO_UPLOAD = 0;
	private final int UPLOAD_STATE_UPLOADING = 1;
	private final int UPLOAD_STATE_HAS_UPLOAD = 2;
	
	private String[] mThemeArray;
	
	private Thread mUploadThread;
	private MediaRecorder mRecorder;
    

	private ITrackService mService = null;
	private ServiceConnection osc = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder binder) {
			mService = ITrackService.Stub.asInterface(binder);
			try {
				if(mInfo.id == TravelerInfo.INFO_INVALID_ID && mService!=null && mService.getTrackServiceState()!= TrackService.TRACK_SERVICE_STATUS_IDLE)
				{
					mInfo.relativeTrackId = mService.getTrackUUID();
					
					setTrack();
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}

		}

		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			
		}
	
	 };
	 
	private Handler mHandler= new Handler()
	{
		@Override
        public void handleMessage(Message msg) {

            switch(msg.what) {
            case HANDLER_MSG_UPDATE_LOC:
            	if(mInfo.locationType == POIInfo.LOCATION_TYPE_UNKNOWN)
            	{
            		Location location = (Location) msg.obj;
            		String provider = location.getProvider();
            		if(provider.equalsIgnoreCase( LocationManager.GPS_PROVIDER))
    				{
            			mInfo.locationType = POIInfo.LOCATION_TYPE_GPS;
            			mInfo.location = location;
            			
            			stopLocating();
            			setLocation(LOCATE_STATE_HAS_LOC,R.string.locate_action);
    				}

            	}

            break;
            
            case HANDLER_MSG_UPLOAD_INFO_START:
            {
            	setUpload(UPLOAD_STATE_UPLOADING, R.string.cancel_upload);
    			mUploadBtn.setEnabled(true);
            }
            break;
            
            case HANDLER_MSG_UPLOAD_INFO_END:
            {
            	if(msg.arg1 == 0)
            	{
            		mInfo.uploadFlag = true;
            		mDB.saveUploadFlag(TravelerInfo.INFO_TYPE_POI, mInfo.id, mInfo.uploadFlag);
            		
            	}
            	updateUploadStatus();
            }
            break;
            	
            }
            
		}

	};
	
	private void sendMessage(int type, Object obj, int extra1)
	{
		Message m = mHandler.obtainMessage(type, extra1, 0, obj);
		mHandler.sendMessage(m);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.poi_layout);
        
        Button exitBtn = (Button) findViewById(R.id.exit_btn);
        exitBtn.setOnClickListener(mExitListener);
        
        Button saveDeleteBtn = (Button) findViewById(R.id.save_delete_btn);
        saveDeleteBtn.setOnClickListener(mSaveDeleteListener);
        
        mThemeArray = getContext().getResources().getStringArray(R.array.poi_type);
        
        mTheme = (Spinner) findViewById(R.id.theme);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.poi_spinner, mThemeArray);
        mTheme.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        mDescription = (EditText) findViewById(R.id.desctiption);
        
        mPhoto = (ImageView) findViewById(R.id.pic_thumb);
        mPhotoBtn = (StatusButton) findViewById(R.id.pic_btn);
        mPhotoBtn.setOnClickListener(mPhotoBtnListener);
        mLocationBtn = (StatusButton) findViewById(R.id.loc_btn);
        mLocationBtn.setOnClickListener(mLocationBtnListener);
        mVoiceBtn = (StatusButton) findViewById(R.id.voice_btn);
        mVoiceBtn.setOnClickListener(mVoiceBtnListener);
        mUploadBtn = (StatusButton) findViewById(R.id.upload_btn);
        mUploadBtn.setOnClickListener(mUploadBtnListener);
        
        mPicIndicator = (IndicateLayout) findViewById(R.id.pic_ind);
        mLocIndicator = (IndicateLayout) findViewById(R.id.location_ind);
        mVoiceIndicator = (IndicateLayout) findViewById(R.id.voice_ind);
        mTrackIndicator = (IndicateLayout) findViewById(R.id.track_ind);
        mUploadIndicator = (IndicateLayout) findViewById(R.id.upload_ind);
	
        mDB = TravelerDB.getInstance(getContext());
        
        int id = getIntent().getIntExtra("INFO_ID", TravelerInfo.INFO_INVALID_ID);
		if(id != TravelerInfo.INFO_INVALID_ID)
		{ 
			saveDeleteBtn.setText(R.string.delete);

			mInfo = (POIInfo) mDB.getTravelerInfo(id, TravelerInfo.INFO_TYPE_POI);
			updateThemeDescription();
			updatePictureStatus();
			updateLocationStatus();
			updateVoiceStatus();

			setTrack();
			updateUploadStatus();
		}
		else
		{
			saveDeleteBtn.setText(R.string.save);
			mInfo = new POIInfo();

			Date date = Calendar.getInstance().getTime();
			mInfo.createTime = date.getTime();
			mInfo.uuid = (int) mInfo.createTime;
			Calendar cal = Calendar.getInstance();
			mInfo.workingFolderPath = TravelerConfig.APP_DATA_FOLDER +
						 String.valueOf(cal.get(Calendar.YEAR))+ "_" +
						 String.valueOf(cal.get(Calendar.MONTH)+1)+ "_" +
						 String.valueOf(cal.get(Calendar.DAY_OF_MONTH))+ "_" +
						 String.valueOf(cal.get(Calendar.HOUR_OF_DAY))+ "_" +
						 String.valueOf(cal.get(Calendar.MINUTE));
			updateUploadStatus();
		}
		
		mWorkFolder = new File(mInfo.workingFolderPath);
		if(!mWorkFolder.exists())
    	{
			mWorkFolder.mkdirs();
    	}
		
		bindService((new Intent()).setClass(getContext(),TrackService.class), osc, 0);
	}
	
	private OnClickListener mExitListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			finish();
		}
		
	};
	
	private OnClickListener mSaveDeleteListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			
			if(mInfo.id == TravelerInfo.INFO_INVALID_ID)
			{
				if(mLocManager != null)
				{
					Toast.makeText(getContext(), R.string.save_when_locating, Toast.LENGTH_LONG).show();
					return;
				}
				mInfo.title = getContext().getResources().getStringArray(R.array.poi_type)[mTheme.getSelectedItemPosition()];
				mInfo.description = mDescription.getText().toString();

				mInfo.id = mDB.savePOIInfo(mInfo);
				if(mInfo.id != TravelerInfo.INFO_INVALID_ID)
				{
					((Button)v).setText(R.string.delete);
					try {
						if(mService!=null && mService.getTrackServiceState()!= TrackService.TRACK_SERVICE_STATUS_IDLE)
						{
							mService.addPOI2Tracking(mInfo.id, mInfo.location);
						}
					} catch (RemoteException e) {
						
						e.printStackTrace();
					}
					updateThemeDescription();
					updatePictureStatus();
					updateLocationStatus();
					updateVoiceStatus();
					updateUploadStatus();
				}
			}
			else
			{
				mDB.deleteTravelerInfo(mInfo.id, TravelerInfo.INFO_TYPE_POI);
				mInfo.id = TravelerInfo.INFO_INVALID_ID;
				finish();
			}
		}
		
	};
	
	private void updateThemeDescription()
	{
		for(int i = 0; i < mThemeArray.length; i++ )
		{
			String t = mThemeArray[i];
			if(t.equalsIgnoreCase(mInfo.title))
			{
				mTheme.setSelection(i);
			}
		}
		mTheme.setEnabled(false);
		mDescription.setText(mInfo.description);
		mDescription.setEnabled(false);
		mDescription.setInputType(InputType.TYPE_NULL); 
	}
	
	private void updateLocationStatus()
	{
		if(mInfo.locationType!=POIInfo.LOCATION_TYPE_UNKNOWN)
		{
			setLocation(LOCATE_STATE_HAS_LOC, R.string.view_loc);
			mLocationBtn.setEnabled(true);
		}
		else
		{
			setLocation(LOCATE_STATE_NO_LOC, R.string.locate);
			mLocationBtn.setEnabled(false);
		}
	}
	
	private OnClickListener mPhotoBtnListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			
			if(mInfo.id == TravelerInfo.INFO_INVALID_ID && mInfo.picPath.length() == 0 && mInfo.picThumb == null)
			{
				//take a pic
				takePicture();
			}
			else if(mInfo.id == TravelerInfo.INFO_INVALID_ID && (mInfo.picPath.length() != 0 && mInfo.picThumb != null))
			{
				//delete or retake pic
				AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

				builder.setItems(R.array.picture_action, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					
					switch(item)
					{
					case 0:		//delete
						{
							removePicture();
						}
						break;
						
					case 1:		//retake
						{
							removePicture();
							takePicture();
						}
						break;
						
					case 2:		//retake
						{
							viewPicture();
						}
						break;
					}
					

				}
				}).create().show();
			}
			else if(mInfo.id != TravelerInfo.INFO_INVALID_ID)
			{
				//view pic 
				viewPicture(mInfo.id);
			}
		}
		
	};
	
	private OnClickListener mLocationBtnListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			if(mInfo.id == TravelerInfo.INFO_INVALID_ID && mInfo.locationType == POIInfo.LOCATION_TYPE_UNKNOWN)
			{
				//take a loc
				takeLocation();
			}
			else if(mInfo.id == TravelerInfo.INFO_INVALID_ID && mInfo.locationType != POIInfo.LOCATION_TYPE_UNKNOWN)
			{
				//delete or view loc
				AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

				builder.setItems(R.array.location_action, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					
					switch(item)
					{
					case 0:		//delete
						{
							removeLocation();
						}
						break;
						
					case 1:		//view
						{
							viewLocation();
						}
						break;
					}
					

				}
				}).create().show();
			}
			else if(mInfo.id != TravelerInfo.INFO_INVALID_ID )
			{
				viewLocation();
			}
		}
		
	};
	
	private OnClickListener mVoiceBtnListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			//Toast.makeText(getContext(), R.string.unsupport, Toast.LENGTH_LONG).show();
			//start to record
			if((mInfo.viocePath==null || mInfo.viocePath.length() == 0) && mInfo.id == TravelerInfo.INFO_INVALID_ID && mRecorder == null)
			{
				recordVoice();
			}
			//stop recording
			else if(mInfo.id == TravelerInfo.INFO_INVALID_ID && mRecorder != null)
			{
				mRecorder.stop();
				mRecorder.release();
				mRecorder = null;
				mInfo.viocePath = makeVoicePath();
				setVoice(VOICE_STATE_HAS_VO, R.string.voice_action);
			
			}
			//voice action
			else if(mInfo.id == TravelerInfo.INFO_INVALID_ID && (mInfo.viocePath!=null || mInfo.viocePath.length() != 0))
			{
				AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

				builder.setItems(R.array.voice_action, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					
					switch(item)
					{
					case 0:		//delete
						{
							removeVoice();
						}
						break;
						
					case 1:		//re-record
						{
							removeVoice();
							recordVoice();
						}
						break;
						
					case 2:		//play
						{
							playVoice();
						}
						break;
					}
					

				}
				}).create().show();
			}
			//play
			else if(mInfo.id != TravelerInfo.INFO_INVALID_ID && (mInfo.viocePath!=null || mInfo.viocePath.length() != 0))
			{
				playVoice();
			}
			
		}
		
	};
	
	private OnClickListener mDeleteListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			removeVoice();
			
		}
		
	};
	
	private void playVoice()
	{
		Dialog dlg = new VoiceDialog(getContext(), mInfo.viocePath, mInfo.id==TravelerInfo.INFO_INVALID_ID?null:mInfo, mDeleteListener);
		dlg.show();
	}
	
	private void recordVoice()
	{
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		mRecorder.setOutputFile(makeVoicePath());
		try {
			mRecorder.prepare();
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		mRecorder.start();
		
		setVoice(VOICE_STATE_RECORDING, R.string.stop_voice);
	}
	
	private void removeVoice()
	{
		if(mInfo.viocePath.length()!=0)
    	{
    		File picFile = new File(mInfo.viocePath);
    		if(picFile.exists())
    		{
    			picFile.delete();
    		}
    	}
		
		mInfo.viocePath = "";
		setVoice(VOICE_STATE_NO_VO, R.string.voice);
	}
	
	private OnClickListener mUploadBtnListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			if(mInfo.uploadFlag)
			{
				return;
			}
			else if(mUploadThread!=null)
			{
				mHandler.removeMessages(HANDLER_MSG_UPLOAD_INFO_END);
				mUploadThread.stop();
				mUploadThread = null;
				updateUploadStatus();
				
				return;
			}
			
			Runnable r = new Runnable()
			{

				@Override
				public void run() {
					sendMessage(HANDLER_MSG_UPLOAD_INFO_START, null,0);
					
					//TODO Idiot: call remote api
					//int ret = Utils.uploadTravelInfo(mInfo, TravelerInfo.INFO_TYPE_POI);
					int ret = 0;
					SystemClock.sleep(1000*5);
					sendMessage(HANDLER_MSG_UPLOAD_INFO_END, null, ret);
					
					mUploadThread = null;
				}
				
			};
			
			mUploadThread = new Thread(r);
			mUploadThread.start();
		}
		
	};
	
    private String makePicturePath()
    {
    	return mInfo.workingFolderPath + "/pic.jpg";
    }
    
    private String makeVoicePath()
    {
    	return mInfo.workingFolderPath + "/voice.amr";
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	if(resultCode != RESULT_OK)
		{
    		return;
		}
    	
    	if(REQUEST_CODE_CAMERA == requestCode)
    	{
    		String path = makePicturePath();
    		mInfo.picPath = path;
    		mInfo.picThumb = Utils.bitmapResize(path);
    		setPicture(PIC_STATE_HAS_PIC, R.string.picture_action);
    	}
    	else if(REQUEST_CODE_PICEDIT == requestCode)
    	{
    		int action = data.getIntExtra("ACTION_CODE", -1);
    		if(action == PictureEditorActivity.PIC_ACTION_REMOVE)
    		{
    			if(mInfo.picPath.length()!=0)
    	    	{
    	    		File picFile = new File(mInfo.picPath);
    	    		if(picFile.exists())
    	    		{
    	    			picFile.delete();
    	    		}
    	    	}
    			
    			mInfo.picPath = "";
    			setPicture(PIC_STATE_NO_PIC, R.string.picture);
    			mInfo.picThumb.recycle();
    			mInfo.picThumb = null;
    		}
    		else if(action == PictureEditorActivity.PIC_ACTION_ROTATE)
    		{
    			mInfo.picThumb.recycle();
    			mInfo.picThumb = Utils.bitmapResize(mInfo.picPath);
    			setPicture(PIC_STATE_HAS_PIC, R.string.picture_action);
    		}
    		
    	}
    	
	}
    
    private OnClickListener mPhotoClickListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			if(mInfo.picPath.length()!=0)
			{
				viewPicture();
				//viewPicture(mInfo.picPath);
			}
		}
		
	};
	
	private void updatePictureStatus()
	{
		if(mInfo.picThumb!=null)
		{
			setPicture(PIC_STATE_HAS_PIC, R.string.view_pic);
			mPhotoBtn.setEnabled(true);
		}
		else
		{
			setPicture(PIC_STATE_NO_PIC, R.string.picture);
			mPhotoBtn.setEnabled(false);
		}
	}
    
	private void setPicture(int picState, int textId)
	{
		switch(picState)
		{
		case PIC_STATE_NO_PIC:
		{
			mPhoto.setBackgroundDrawable(null);
			mPhoto.setVisibility(View.GONE);
			mPicIndicator.mIcon.setVisibility(View.GONE);
			mPicIndicator.mProgressBar.setVisibility(View.GONE);
			mPicIndicator.mInfo.setVisibility(View.GONE);
    		
			mPhotoBtn.setText(textId);
			mPhotoBtn.showIcon();
		}
		break;
		
		case PIC_STATE_HAS_PIC:
		{
			mPhoto.setVisibility(View.VISIBLE);
			mPhoto.setImageBitmap(mInfo.picThumb);
			mPhoto.setBackgroundResource(R.drawable.popup);
			mPhoto.setOnClickListener(mPhotoClickListener);
			
			mPicIndicator.mIcon.setVisibility(View.VISIBLE);
			mPicIndicator.mProgressBar.setVisibility(View.GONE);
			mPicIndicator.mInfo.setVisibility(View.GONE);
    		
			mPhotoBtn.setText(textId);
			mPhotoBtn.showIcon();
		}
		break;
		}

	}
	
	private void takePicture()
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String path = makePicturePath();
		File out = new File(path);
		Uri uri = Uri.fromFile(out);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		
		startActivityForResult(intent, REQUEST_CODE_CAMERA);
	}
	
	private void removePicture()
	{
		if(mInfo.picPath.length()!=0)
    	{
    		File picFile = new File(mInfo.picPath);
    		if(picFile.exists())
    		{
    			picFile.delete();
    		}
    	}
	
		setPicture(PIC_STATE_NO_PIC, R.string.picture);

    	mInfo.picPath = "";
    	if(mInfo.picThumb!=null)
    	{
    		mInfo.picThumb.recycle();
    		mInfo.picThumb = null;
    	}
	}
	
	private void viewPicture()
	{
		if(mInfo.id != TravelerInfo.INFO_INVALID_ID)
		{
			viewPicture(mInfo.id);
		}
		else
		{
			viewPicture(mInfo.picPath);
		}
	}
	
    private void viewPicture(String path)
    {
    	if(path == null || path.length() == 0)
    	{
    		return;
    	}
    	
    	Intent i = new Intent(getContext(), PictureEditorActivity.class);
		i.putExtra("PIC_PATH", path);
		startActivityForResult(i,REQUEST_CODE_PICEDIT);
    }
    
    private void viewPicture(int id)
    {
    	if(id == TravelerInfo.INFO_INVALID_ID)
    	{
    		return;
    	}
    	
    	Intent i = new Intent(getContext(), PictureViewerActivity.class);
		i.putExtra("INFO_ID", id);
		startActivityForResult(i,REQUEST_CODE_PICVIEW);
		
    }
    
    private void updateUploadStatus()
	{
		if(mInfo.uploadFlag)
		{
			setUpload(UPLOAD_STATE_HAS_UPLOAD, R.string.upload);
			mUploadBtn.setEnabled(false);
		}
		else
		{
			setUpload(UPLOAD_STATE_NO_UPLOAD, R.string.upload);
			mUploadBtn.setEnabled(mInfo.id!=TravelerInfo.INFO_INVALID_ID?true:false);
		}
	}
    
    private void setUpload(int uploadState, int textId)
    {
    	switch(uploadState)
    	{
    	case UPLOAD_STATE_NO_UPLOAD:
    	{
    		mUploadIndicator.mIcon.setVisibility(View.GONE);
    		mUploadIndicator.mProgressBar.setVisibility(View.GONE);
    		mUploadIndicator.mInfo.setVisibility(View.GONE);

    		mUploadBtn.setText(textId);
    		mUploadBtn.showIcon();
    	}
    	break;
    	
    	case UPLOAD_STATE_UPLOADING:
    	{
    		mUploadIndicator.mIcon.setVisibility(View.GONE);
    		mUploadIndicator.mProgressBar.setVisibility(View.GONE);
    		mUploadIndicator.mInfo.setVisibility(View.GONE);
    		
    		mUploadBtn.setText(textId);
    		mUploadBtn.showProgressBar();
    	}
    	break;
    	
    	case UPLOAD_STATE_HAS_UPLOAD:
    	{
    		mUploadIndicator.mProgressBar.setVisibility(View.GONE);
    		mUploadIndicator.mInfo.setVisibility(View.GONE);
    		mUploadIndicator.mIcon.setVisibility(View.VISIBLE);
    		
    		mUploadBtn.setText(textId);
    		mUploadBtn.showIcon();
    	}
    	break;
    	}
    }
    
    
    private void setLocation(int locationState, int textId)
    {
    	switch(locationState)
    	{
    	case LOCATE_STATE_NO_LOC:
    	{
    		mLocIndicator.mIcon.setVisibility(View.GONE);
    		mLocIndicator.mProgressBar.setVisibility(View.GONE);
    		mLocIndicator.mInfo.setVisibility(View.GONE);

    		mLocationBtn.setText(textId);
            mLocationBtn.showIcon();
    	}
    	break;
    	
    	case LOCATE_STATE_LOCATING:
    	{
    		mLocIndicator.mIcon.setVisibility(View.GONE);
    		mLocIndicator.mProgressBar.setVisibility(View.GONE);
    		mLocIndicator.mInfo.setVisibility(View.GONE);
    		
    		mLocationBtn.setText(textId);
            mLocationBtn.showProgressBar();
    	}
    	break;
    	
    	case LOCATE_STATE_HAS_LOC:
    	{
    		mLocIndicator.mProgressBar.setVisibility(View.GONE);
    		mLocIndicator.mInfo.setVisibility(View.GONE);
    		mLocIndicator.mIcon.setVisibility(View.VISIBLE);
    		
    		mLocationBtn.setText(textId);
    		mLocationBtn.showIcon();
    	}
    	break;
    	}
    }
    
    private void updateVoiceStatus()
	{
		if(mInfo.viocePath != null && mInfo.viocePath.length() != 0)
		{
			setVoice(VOICE_STATE_HAS_VO, R.string.play_voice);
			mVoiceBtn.setEnabled(true);
		}
		else
		{
			setVoice(VOICE_STATE_NO_VO, R.string.voice);
			mVoiceBtn.setEnabled(false);
		}
	}
    
    private void setVoice(int voiceState, int textId)
    {
    	switch(voiceState)
    	{
    	case VOICE_STATE_NO_VO:
    	{
    		mVoiceIndicator.mIcon.setVisibility(View.GONE);
    		mVoiceIndicator.mProgressBar.setVisibility(View.GONE);
    		mVoiceIndicator.mInfo.setVisibility(View.GONE);

    		mVoiceBtn.setText(textId);
            mVoiceBtn.showIcon();
    	}
    	break;
    	
    	case VOICE_STATE_RECORDING:
    	{
    		mVoiceIndicator.mIcon.setVisibility(View.GONE);
    		mVoiceIndicator.mProgressBar.setVisibility(View.GONE);
    		mVoiceIndicator.mInfo.setVisibility(View.GONE);
    		
    		mVoiceBtn.setText(textId);
            mVoiceBtn.showProgressBar();
    	}
    	break;
    	
    	case VOICE_STATE_HAS_VO:
    	{
    		mVoiceIndicator.mProgressBar.setVisibility(View.GONE);
    		mVoiceIndicator.mInfo.setVisibility(View.GONE);
    		mVoiceIndicator.mIcon.setVisibility(View.VISIBLE);
    		
    		mVoiceBtn.setText(textId);
    		mVoiceBtn.showIcon();
    	}
    	break;
    	}
    }
    
    private void setTrack()
    {
    	if(mInfo.relativeTrackId == POIInfo.INFO_INVALID_ID)
		{
    		mTrackIndicator.mIcon.setVisibility(View.GONE);
    		mTrackIndicator.mProgressBar.setVisibility(View.GONE);
    		mTrackIndicator.mInfo.setVisibility(View.GONE);
			return;
		}
		
    	mTrackIndicator.mIcon.setVisibility(View.VISIBLE);
    	mTrackIndicator.mProgressBar.setVisibility(View.GONE);
		mTrackIndicator.mInfo.setVisibility(View.GONE);
    }
    
    private void stopLocating()
    {
    	mLocManager.removeUpdates(mPositionListener);
		mLocManager = null;
		
		
    }
    
    private void takeLocation()
    {
    	if(mLocManager!=null)
    	{
    		stopLocating();
    		setLocation(LOCATE_STATE_NO_LOC, R.string.locate);
    		
    		return;
    	}
    	
    	mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
        List<String> privoderList = mLocManager.getProviders(true);
        boolean isGPSEnable = false;
        for(String provider: privoderList)
        {
        	if(provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER))
        	{
        		isGPSEnable = true;
        	}
        	
        }
        
        if(isGPSEnable)
        {
        	mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mPositionListener);
        	setLocation(LOCATE_STATE_LOCATING, R.string.cancel_locate);
        }
        else
        {
        	Toast.makeText(getContext(), R.string.gps_not_enable, Toast.LENGTH_LONG).show();
        }
  
    }
    
    private  LocationListener mPositionListener = new  LocationListener()
    {

		@Override
		public void onLocationChanged(Location location) {
			
			sendMessage(HANDLER_MSG_UPDATE_LOC, location, 0);
		}

		@Override
		public void onProviderDisabled(String provider) {
			
	
		}

		@Override
		public void onProviderEnabled(String provider) {
			

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			

		}
    	
    };
    
    private void removeLocation()
    {
    	mInfo.locationType = POIInfo.LOCATION_TYPE_UNKNOWN;
    	mInfo.location = null;
    	setLocation(LOCATE_STATE_NO_LOC, R.string.locate);
    }
    
    private void viewLocation()
    {
    	if(mInfo.locationType == POIInfo.LOCATION_TYPE_UNKNOWN)
    	{
    		return;
    	}
    	
    	Intent i = new Intent(getContext(), MapInfoActivity.class);
    	if(mInfo.id != TravelerInfo.INFO_INVALID_ID)
    	{
    		i.putExtra("INFO_ID", mInfo.id);
    	}
    	else
    	{
    		i.putExtra("LAT", mInfo.location.getLatitude());
    		i.putExtra("LON", mInfo.location.getLongitude());
    		i.putExtra("ALT", mInfo.location.getAltitude());
    		i.putExtra("TIME", mInfo.createTime);
    	}
		startActivity(i);
		
    	/*if(Utils.detectNetwork(getContext()))
		{
    		//map view
			Intent i = new Intent(getContext(), MapInfoActivity.class);
			i.putExtra("INFO_ID", mInfo.id);
			startActivity(i);
		}
		else
		{
			//dialog view
			AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
			Resources res = getContext().getResources();
			builder.setTitle(R.string.loc_info).setMessage(res.getString(R.string.lon)+": "+mInfo.location.getLongitude() + res.getString(R.string.degree_unit) + "\n"
												+ res.getString(R.string.lat)+": "+mInfo.location.getLatitude() + res.getString(R.string.degree_unit) + "\n"
												+ res.getString(R.string.alt)+": "+mInfo.location.getAltitude() + res.getString(R.string.distance_unit) + "\n")
			.create().show();
		}*/
    }
    
	private Context getContext()
    {
    	return POIActivity.this;
    }
	
	
	
	@Override
	protected void onDestroy() {
		
		if(mLocManager!=null)
		{
			mLocManager.removeUpdates(mPositionListener);
			mLocManager = null;
		}
		
		unbindService(osc);

		mWorkFolder.delete();

		super.onDestroy();
	}
	
}
